#include "log.h"
#include <strsafe.h>
#include <stdio.h>

VOID Log(LPCTSTR fmt, ...)
{
#ifndef NDEBUG
    CHAR szDbgMsg[10240];
    va_list ap;
    va_start(ap, fmt);
    vsprintf_s(szDbgMsg, fmt, ap);
    va_end(ap);

#ifdef _CONSOLE
    printf(szDbgMsg);
#else 
    OutputDebugString(szDbgMsg);
#endif 
#endif 
}

void Err(LPCTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&lpMsgBuf,
        0, NULL);

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
        (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
    StringCchPrintf((LPTSTR)lpDisplayBuf,
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"),
        lpszFunction, dw, lpMsgBuf);

#ifdef _CONSOLE
    printf((LPCTSTR)lpDisplayBuf);
#else 
    OutputDebugString((LPCTSTR)lpDisplayBuf);
#endif 

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}